/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pdf.digitalSignature;

import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfSignatureAppearance;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;

/**
 *
 * @author rajasekha.burepalli
 */
public class DigitalSignature {

    public static void main(String args[]) throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, DocumentException {
        String inpuPDFPath = "B:\\digitalSignatures\\input\\Java Concurrency _ Multithreading Tutorial _ tutorials.jenkov.pdf";
        System.out.println("inpuPDFPath:" + inpuPDFPath);
        String outputSignedPdfPath = "B:\\digitalSignatures\\digitalSignatureOuput\\Java Concurrency _ Multithreading Tutorial _ tutorials.jenkov.PDF";
        System.out.println("outputSignedPdfPath:" + outputSignedPdfPath);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        String jksFile = "B:\\digitalSignatures\\rajasekhar_keystore.jks";
        String signaturePassword = "m@123uni";
        ks.load(new FileInputStream(jksFile), signaturePassword.toCharArray());
        String alias = (String) ks.aliases().nextElement();
        PrivateKey key = (PrivateKey) ks.getKey(alias, signaturePassword.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);
        FileOutputStream fout = new FileOutputStream(outputSignedPdfPath);
        PdfStamper stp = PdfStamper.createSignature(new PdfReader(inpuPDFPath), fout, '\0');
        stp.setEncryption(false, "custPass123", "ownerPass123", PdfWriter.AllowPrinting | PdfWriter.AllowCopy | PdfWriter.AllowScreenReaders | PdfWriter.AllowDegradedPrinting);
        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        sap.setReason("Digitally Signed Portable Document");
        sap.setLocation("Cuddapah");
        sap.setContact("1234567890");        
        sap.setVisibleSignature(new Rectangle(250, 750, 350, 700), 1, null);
        stp.close();
    }
}
